import { Component, OnInit,Input,Output,ElementRef,EventEmitter,ViewChild } from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import { Router, ActivatedRoute,Params} from '@angular/router';
import {MenuService} from '../../services/menu.service';
import {TreeNode} from 'primeng/api';
import {Tree} from 'primeng/tree';
import {Message} from 'primeng/components/common/api';
import {trigger,state,style,animate,transition} from '@angular/animations';
import {GetDatasetlistService} from '../../services/get-datasetlist.service';
import {ChartService} from '../../services/chart/chart.service';
import{ChartsService} from '../../services/charts.service'
import {DataService} from '../../services/dataservice'
import {DatasService} from '../../services/data/data.service'
import {TreeService} from '../../services/tree.service';
import {HttpUtilService} from '../../services/common/http-util.service';
import {CityServie} from '../../services/city.service';
import {HttpClient} from '@angular/common/http';

import { ECharts } from "echarts";
import* as echarts from 'echarts';

declare var $: any;
import * as _ from 'underscore';

@Component({
  selector: 'app-widget',
  templateUrl: './widget.component.html',
  styleUrls: ['./widget.component.css'],
   //定义动画
   animations: [
    trigger('shrinkOut', [
      state('in', style({height: '0'})),
      transition('* => void', [
        // style({height: '*'),
        animate('100ms ease-in')
      ]),
      transition('void => *', [
        // style({height: '*'),
        animate('100ms ease-out')
      ]),
    ])
  ]
})
export class WidgetComponent implements OnInit {


     menuarr ='图表设计';
     storage : any;
     provinces:any;
     Chart: ECharts;
     public widgetList:any;     //树形目录数据
     private item:string;       //tab选项卡参数
     columns=[]


//   translate = $filter('translate');
  updateUrl = "dashboard/updateWidget.do";
  liteMode = false;
  tab = 'preview_widget2';

  chartType:string=''        //图表类型
  deleteShow:boolean=false   //删除确认

 //界面控制
 schema=null;
 loading = false;
 toChartDisabled = true;
 optFlag = '';
 alerts = [];
 treeData=[];
 originalData = [];       //树形目录的数据
 treeID = 'widgetTreeID'; // Set to a same value with treeDom
 modalshow = false;

//获取table-style、pie、group、filters、keys的值
tablearray:any;


 datasource;
 widgetName:any;
 widgetCategory;
 widgetId;
 masterDashboardDateFilterColumn;
 masterDashboardDateFilterFormat;
 curWidget = {
    config:{
        chart_type:'',
        option:{},
        selects:{},
        values:[],
        groups:{},
        keys:{},
        filters:{},
        valueAxis:'',
        styles:[]
    },
    expressions:[],
    filterGroups:[],
    datasetId:'',
    query:''
 };
 previewDivWidth = 12;
 expressions = [];
 customDs = false;
 loadFromCache = true;
 filterSelect = {};
 verify = {widgetName: true};
 params = [];
 curDataset;
 datasetList:any;
 isActive:boolean;
 loadingPre:boolean;
 viewQueryMoal:boolean
 tableshow:boolean;       //表格显示
 widgetTitle:string;      //树形目录的标题，根据点击的路由显示
 classObject:object={}    //树形目录标题图标
 WIDGET:boolean;          //树形目录标题图标显示

  constructor(
      private http: HttpClient,
      public translate:TranslateService,
      private activated: ActivatedRoute,
      private router:Router,
      private menservice:MenuService,
      private getdata:GetDatasetlistService,
      private chartService: ChartService,
      private chartsservice:ChartsService,
    private httpUtilService:HttpUtilService,
    private element:ElementRef,
    private treeservice:TreeService,
    private cityservice:CityServie,
    private dataService:DataService,
    private dataservice:DatasService
    ) {
        // console.log(treeservice)
        //instant
    translate.addLangs(['zh','en']);                          //添加语言支持
    translate.setDefaultLang('en');                           //设置默认语言
    let broswerLang = translate.getBrowserLang();              //获取浏览器支持的语言
    console.log(broswerLang)                                   //zh
    translate.use(broswerLang.match(/zh|en/) ? broswerLang : 'en');
   }



  //图表类型初始化
  //value  图表类型
  chart_types = [
    {
        name: this.translate.instant('CONFIG.WIDGET.TABLE'), 
        value: 'table', 
        class: 'cTable',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.LINE_BAR'), 
        value: 'line', class: 'cLine',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.CONTRAST'), 
        value: 'contrast', class: 'cContrast',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_2')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.SCATTER'), value: 'scatter', class: 'cScatter',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.PIE'), value: 'pie', class: 'cPie',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.KPI'), value: 'kpi', class: 'cKpi',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.FUNNEL'), value: 'funnel', class: 'cFunnel',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.SANKEY'), value: 'sankey', class: 'cSankey',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.RADAR'), value: 'radar', class: 'cRadar',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.MAP'), value: 'map', class: 'cMap',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.GAUGE'), value: 'gauge', class: 'cGauge',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.WORD_CLOUD'), value: 'wordCloud', class: 'cWordCloud',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.TREE_MAP'), value: 'treeMap', class: 'cTreeMap',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        measure:this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.HEAT_MAP_CALENDER'),
         value: 'heatMapCalendar',
         class: 'cHeatMapCalendar',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.HEAT_MAP_TABLE'), 
        value: 'heatMapTable', 
        class: 'cHeatMapTable',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        measure:this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.LIQUID_FILL'), value: 'liquidFill', class: 'cLiquidFill',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.AREA_MAP'), 
        value: 'areaMap', class: 'cAreaMap',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.CHINA_MAP'), 
        value: 'chinaMap', 
        class: 'cChinaMap',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.CHINA_MAP_BMAP'), 
        value: 'chinaMapBmap', 
        class: 'cChinaMapBmap',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_0_MORE'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_MORE')
    },
    {
        name: this.translate.instant('CONFIG.WIDGET.RELATION'), 
        value: 'relation', 
        class: 'cRelation',
        row: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_2'),
        column: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1_2'),
        measure: this.translate.instant('CONFIG.WIDGET.TIPS_DIM_NUM_1')
    }
]

chart_types_status = {
  "line": true, "pie": true, "kpi": true, "table": true,
  "funnel": true, "sankey": true, "radar": true, "map": true,
  "scatter": true, "gauge": true, "wordCloud": true, "treeMap": true,
  "heatMapCalendar": true, "heatMapTable": true, "liquidFill": true,
  "areaMap": true, "contrast": true,"chinaMap":true,"chinaMapBmap":true,"relation":true
}

value_aggregate_types = [
  {name: 'sum', value: 'sum'},
  {name: 'count', value: 'count'},
  {name: 'avg', value: 'avg'},
  {name: 'max', value: 'max'},
  {name: 'min', value: 'min'},
  {name: 'distinct', value: 'distinct'}
]

kpi_styles = [
  {name: this.translate.instant('CONFIG.WIDGET.AQUA'), value: 'bg-aqua'},
  {name: this.translate.instant('CONFIG.WIDGET.RED'), value: 'bg-red'},
  {name: this.translate.instant('CONFIG.WIDGET.GREEN'), value: 'bg-green'},
  {name: this.translate.instant('CONFIG.WIDGET.YELLOW'), value: 'bg-yellow'}
]

treemap_styles = [
  {name: this.translate.instant('CONFIG.WIDGET.RANDOM'), value: 'random'},
  {name: this.translate.instant('CONFIG.WIDGET.MULTI'), value: 'multi'},
  {name: this.translate.instant('CONFIG.WIDGET.BLUE'), value: 'blue'},
  {name: this.translate.instant('CONFIG.WIDGET.RED'), value: 'red'},
  {name: this.translate.instant('CONFIG.WIDGET.GREEN'), value: 'green'},
  {name: this.translate.instant('CONFIG.WIDGET.YELLOW'), value: 'yellow'},
  {name: this.translate.instant('CONFIG.WIDGET.PURPLE'), value: 'purple'}
]

heatmap_styles = [
  {name: this.translate.instant('CONFIG.WIDGET.BLUE'), value: 'blue'},
  {name: this.translate.instant('CONFIG.WIDGET.RED'), value: 'red'},
  {name: this.translate.instant('CONFIG.WIDGET.GREEN'), value: 'green'},
  {name: this.translate.instant('CONFIG.WIDGET.YELLOW'), value: 'yellow'},
  {name: this.translate.instant('CONFIG.WIDGET.PURPLE'), value: 'purple'}
]

heatmap_date_format = [
  {name: 'yyyy-MM-dd', value: 'yyyy-MM-dd'},
  {name: 'yyyy/MM/dd', value: 'yyyy/MM/dd'},
  {name: 'yyyyMMdd', value: 'yyyyMMdd'}
];

liquid_fill_style = [
  {name:this.translate.instant('CONFIG.WIDGET.CIRCLE'), value: 'circle'},
  {name: this.translate.instant('CONFIG.WIDGET.PIN'), value: 'pin'},
  {name:this.translate.instant('CONFIG.WIDGET.RECT'), value: 'rect'},
  {name: this.translate.instant('CONFIG.WIDGET.ARROW'), value: 'arrow'},
  {name: this.translate.instant('CONFIG.WIDGET.TRIANGLE'), value: 'triangle'},
  {name: this.translate.instant('CONFIG.WIDGET.ROUND_RECT'), value: 'roundRect'},
  {name: this.translate.instant('CONFIG.WIDGET.SQUARE'), value: 'square'},
  {name: this.translate.instant('CONFIG.WIDGET.DIAMOND'), value: 'diamond'}
];
configRule = {
  line: {keys: 2, groups: -1, filters: -1, values: 2},
  pie: {keys: 2, groups: -1, filters: -1, values: 2},
  kpi: {keys: 0, groups: 0, filters: -1, values: 1},
  table: {keys: -1, groups: -1, filters: -1, values: -1},
  funnel: {keys: -1, groups: 0, filters: -1, values: 2},
  sankey: {keys: 2, groups: 2, filters: -1, values: 1},
  radar: {keys: 2, groups: -1, filters: -1, values: 2},
  map: {keys: 2, groups: -1, filters: -1, values: 2},
  scatter: {keys: 2, groups: -1, filters: -1, values: 2},
  gauge: {keys: 0, groups: 0, filters: -1, values: 1},
  wordCloud: {keys: 2, groups: 0, filters: -1, values: 1},
  treeMap: {keys: 2, groups: 0, filters: -1, values: 1},
  areaMap: {keys: 2, groups: -1, filters: -1, values: 1},
  heatMapCalendar: {keys: 1, groups: 0, filters: -1, values: 1},
  heatMapTable: {keys: 2, groups: 2, filters: -1, values: 1},
  liquidFill: {keys: 0, groups: 0, filters: -1, values: 1},
  contrast: {keys: 1, groups: 0, filters: -1, values: 2},
  chinaMap:{keys: 2, groups: -1, filters: -1, values: 2},
  chinaMapBmap:{keys: 2, groups: -1, filters: -1, values: 2},
  relation: {keys: 2, groups: 2, filters: -1, values: 1}
};


groupdata(data){
    console.log(data)
}
keysdata(data){
    console.log(data)
}
filtersdata(data){
    console.log(data)
}
funneldata(data){
    console.log(data)
}

//获取getDatasetList.do数据
public loadDataset (callback:any){  
    this.getdata.get().subscribe(function(data){
       console.log(data)
       this.datasetList=data;
    //    callback()
   })
} 


searchNode() {
    var para = {wgtName: '', dsName: '', dsrName: ''};

    //map widgetList to list (add datasetName and datasourceName)
    var list = this.widgetList.map(function (w) {
        var ds = _.find(this.datasetList, function (obj) {
            return obj.id == w.data.datasetId
        });
        var dsrName = '';
        var dsr;
        if (ds) {
            dsr = _.find(this.datasourceList, function (obj) {
                return obj.id == ds.data.datasource
            });
        } else if (w.data.datasource) {
            dsr = _.find(this.datasourceList, function (obj) {
                return obj.id == w.data.datasource
            });
        }
        return {
            "id": w.id,
            "name": w.name,
            "categoryName": w.categoryName,
            'dateFilter': w.dateFilter,
            'dateFormat': w.dateFormat,
            "datasetName": ds ? ds.name : '',
            "datasourceName": dsr ? dsr.name : dsrName
        };
    });
}

getTreeMenu(){
    const _this=this;
    this.treeservice.getData().then(function(res){
        console.log(res)
        _this.widgetList=res.menus
        console.log(_this.widgetList)
    })
}

getWidgetList (callback:any) {
    this.getTreeMenu();
        if (callback) {
            callback();
        };
        this.searchNode()
};
  ngOnInit() {
      this.initRequests();
    
    console.log(this.activated.snapshot.params.id)
    if(this.activated.snapshot.params.id==7){
        //动态显示标题图标
        this.WIDGET=true;
        this.classObject={
            "fa":this.WIDGET,
            "fa-bar-chart-o":this.WIDGET
        }
        console.log(this.translate.instant('CONFIG.WIDGET.WIDGET'))
        this.widgetTitle=this.translate.instant('CONFIG.WIDGET.WIDGET');
        console.log(this.widgetTitle)
    }

    this.activated.params.subscribe(params => {
        console.info(params);
      });

      this.cityservice.getCity().subscribe(function(data){
        this.provinces = data;
      })

        this.loadDataset(null)
  }

  ngAfterViewInit(){
    this.getTreeMenu();


  }

  ngOnDestroy(){
    $('#preview').html('')
  }

  //动画展示
  toToggle(){
    this.isActive=!this.isActive
    console.log(this.isActive)
  }


//   msgs: Message[];
//   selectedFile: TreeNode;
//   nodeSelect(data){
//     this.msgs = [];
//     this.msgs.push({severity: 'info', summary: 'Node Selected', detail: data.node.label});
//   }
//   nodeUnselect(event) {
//     this.msgs = [];
//     this.msgs.push({severity: 'info', summary: '没有选择节点', detail: event.node.label});
//   }

  switchLiteMode (mode) {
    // if (mode) {
    //     this.liteMode = mode;
    //     this.$parent.$parent.liteMode = mode;
    // } else {
    //     this.liteMode = !this.liteMode;
    //     this.$parent.$parent.liteMode = this.liteMode;
    // }
    this.liteMode=!this.liteMode
}


//dashboard/getDatasourceList.do  获取数据源

// $http.get("dashboard/getDatasourceList.do").success(function (response) {
//     $scope.datasourceList = response;
//     getCategoryList();
//     getWidgetList(function () {
//         if ($stateParams.id) {
//             $scope.editWgt(_.find($scope.widgetList, function (w) {
//                 return w.id == $stateParams.id;
//             }));
//         } else if ($stateParams.id == null && $stateParams.datasetId) {
//             $scope.newWgt({datasetId: parseInt($stateParams.datasetId)});
//             $scope.loadData();
//         }
//     });
// });

getCurDatasetName () {
    if (this.customDs) {
        return this.translate.instant('CONFIG.WIDGET.NEW_QUERY');
    } else {
        var curDS = _.find(this.datasetList, function (ds) {
            return ds.id == this.curWidget.datasetId;
        });
        return curDS ? curDS.name : null;
    }
}

public datasetGroup (item) {
    return item.categoryName;
};


getCategoryList () {
    // $http.get("dashboard/getWidgetCategoryList.do").success(function (response) {
    //     this.categoryList = response;
    //     $("#widgetName").autocomplete({
    //         source: this.categoryList
    //     });
    // });
};


    // $uibModal.open({
        // templateUrl: 'org/cboard/view/config/modal/exp.html',
        // windowTemplateUrl: 'org/cboard/view/util/modal/window.html',
        // backdrop: false,
        // size: 'lg',
        // scope: $scope,
        // controller: function ($scope, $uibModalInstance) {
        //     $scope.data = data;
        //     $scope.curWidget = curWidget;
        //     $scope.columnObjs = columnObjs;
        //     $scope.aggregate = aggregate;
        //     $scope.expressions = curWidget.expressions;
        //     $scope.alerts = [];
        //     $scope.close = function () {
        //         $uibModalInstance.close();
        //     };
        //     var columns = _.map(columnObjs, function (o) { return o.column; });
        //     $scope.expAceOpt = expEditorOptions($scope.selects, aggregate, function(_editor) {
        //         $scope.expAceEditor = _editor;
        //         $scope.expAceSession = _editor.getSession();
        //         _editor.focus();
        //     });
        //     $scope.addToken = function (str, agg) {
        //         var editor = $scope.expAceEditor;
        //         editor.session.insert(editor.getCursorPosition(), str);
        //         editor.focus();
        //         if (agg) editor.getSelection().moveCursorLeft();
        //     };
        //     $scope.verify = function () {
        //         $scope.alerts = [];
        //         var v = verifyAggExpRegx($scope.data.expression);
        //         $scope.alerts = [{
        //             msg: v.isValid ? this.translate.instant("COMMON.SUCCESS") : v.msg,
        //             type: v.isValid ? 'success' : 'danger'
        //         }];
        //     };
        //     $scope.ok = function () {
        //         if (!$scope.data.alias) {
        //             ModalUtils.alert(this.translate.instant('CONFIG.WIDGET.ALIAS') + this.translate.instant('COMMON.NOT_EMPTY'), "modal-warning", "lg");
        //             return;
        //         }
        //         $scope.data.expression = $scope.expAceSession.getValue();
        //         ok($scope.data);
        //         $uibModalInstance.close();
        //     };
        // }
//     });
// };

 loadData () {
    this.toChartDisabled = false;
    this.newConfig();
    this.filterSelect = {};
    this.loadDataset(function () {
        this.curWidget.expressions = [];
        this.loadDsExpressions();
        this.curWidget.filterGroups = [];
        this.loadDsFilterGroups();
        this.buildSchema();
    });
    this.cleanPreview();
};

newWgt (curWidget) {
    // this.curWidget = {};
    if (curWidget) {
        this.curWidget = curWidget;
    }
    // this.curWidget.config = {};
    // this.curWidget.config.option = {};
    // this.curWidget.expressions = [];
    // this.curWidget.filterGroups = [];
    // this.curWidget.query = {};
    this.datasource = null;
    this.widgetName = null;
    this.widgetCategory = null;
    this.widgetId = null;
    this.optFlag = 'new';
    this.customDs = false;
    this.schema = null;
    this.liteMode = false;
    this.cleanPreview();
    this.addValidateWatch();
};

loadDsFilterGroups () {
    // if (!this.customDs) {
    //     var fg = _.find(this.datasetList, function (ds) {
    //         return ds.id == this.curWidget.datasetId;
    //     }).data.filters;
    //     if (fg) {
    //         _.each(fg, function (e) {
    //             this.curWidget.filterGroups.push(e);
    //         });
    //     }
    // }
};


public loadDsExpressions () {
    // if (!$scope.customDs) {
    //     var dsExp = _.find($scope.datasetList, function (ds) {
    //         return ds.id == $scope.curWidget.datasetId;
    //     }).data.expressions;
    //     if (dsExp) {
    //         _.each(dsExp, function (e) {
    //             $scope.curWidget.expressions.push(e);
    //         });
    //     }
    // }
};

public addWatch () {
    // this.$watch('curWidget.config.keys', changeChartStatus, true);
    // $scope.$watch('curWidget.config.groups', changeChartStatus, true);
    // $scope.$watch('curWidget.config.values', changeChartStatus, true);
    // $scope.$watch('curWidget.config.filters', changeChartStatus, true);
    // this.addHelpMessage();
    // addValidateWatch();
};

public addHelpMessage () {
    // var rowKey = 'HELP_MESSAGE.' + $scope.curWidget.config.chart_type.toUpperCase() + ".ROW";
    // var columnKey = 'HELP_MESSAGE.' + $scope.curWidget.config.chart_type.toUpperCase() + ".COLUMN";
    // var filterKey = 'HELP_MESSAGE.' + $scope.curWidget.config.chart_type.toUpperCase() + ".FILTER";
    // var valueKey = 'HELP_MESSAGE.' + $scope.curWidget.config.chart_type.toUpperCase() + ".VALUE";
    // var row = this.translate.instant(rowKey) == rowKey ? null : this.translate.instant(rowKey);
    // var column = this.translate.instant(columnKey) == columnKey ? null : this.translate.instant(columnKey);
    // var filter = this.translate.instant(filterKey) == filterKey ? null : this.translate.instant(filterKey);
    // var value = this.translate.instant(valueKey) == valueKey ? null : this.translate.instant(valueKey);
    // this.helpMessage = {row: row, column: column, filter: filter, value: value};
};

addValidateWatch () {
    // this.$watch('widgetName', clearAlert, true);
    // this.$watch('curWidget.datasetId', clearAlert, true);
};
clearAlert () {
    this.alerts = [];
    this.verify = {widgetName: true};
};
validation () {
    this.alerts = [];
    this.verify = {widgetName: true};
    if (!this.widgetName) {
        this.alerts.push({
                severity:'warn', 
                summary:'Warn Message', 
                detail:'图表名不能为空'
        });
        this.verify = {widgetName: false};
        $("#widgetName").focus();
        return false;
    }else{
        this.alerts=[]
    }
    if (this.customDs == false && this.curWidget.datasetId == undefined) {
        this.alerts.push({
                severity:'warn', 
                summary:'Warn Message', 
                detail:'图表名不能为空'
        })
        return false;
    }else{
        this.alerts=[]
    }
    if (this.customDs == true) {
        for (var i = 0; i < this.params.length; i++) {
            var name = this.params[i].name;
            var label = this.params[i].label;
            var required = this.params[i].required;
            var value = this.curWidget.query[name];
            if (required == true && value != '' && (value == undefined || value == "")) {
                var pattern = /([\w_\s\.]+)/;
                var msg = pattern.exec(label);
                if (msg && msg.length > 0)
                    msg = this.translate.instant(msg[0]);
                else
                    msg = label;
                this.alerts.push({
                    severity:'warn', 
                    summary:'Warn Message', 
                    detail:'图表名不能为空'
                })
                this.verify[name] = false;
                return false;
            }
        }
    }
    return true;
};

changeChartStatus () {
    for (var type in this.chart_types_status) {
        var rule = this.configRule[type];
        var config = this.curWidget.config;
        var flattenValues = [];
        _.each(config.values, function (v) {
            flattenValues = flattenValues.concat(v.cols);
        });
        if (_.size(config.keys) == 0 && _.size(config.groups) == 0 && _.size(flattenValues) == 0) {
            r = false;
        } else {
            for (var k in rule) {
                var r = true;
                if (rule[k] == 2) {
                    if (k == 'values') {
                        r = (_.size(flattenValues) >= 1);
                        if (type == 'contrast') {
                            r = (_.size(flattenValues) == 2); //限制values数量为2
                        }
                    } else {
                        r = (_.size(config[k]) >= 1);
                    }
                } else if (rule[k] != -1) {
                    if (k == 'values') {
                        r = (_.size(flattenValues) == rule[k]);
                    } else {
                        r = (_.size(config[k]) == rule[k]);
                    }
                }
                if (!r) {
                    this.chart_types_status[type] = r;
                    break;
                }
            }
        }
        this.chart_types_status[type] = r;
    }
};

chartype:any;   //图表类型

changeChart (chart_type) {
    if (!this.chart_types_status[chart_type]) {
        return;
    }
    
    this.chartype=chart_type;
    var oldConfig = JSON.parse(JSON.stringify(this.curWidget.config));
    // this.curWidget.config = {};
    this.curWidget.config.option = {};
    this.curWidget.config.chart_type = chart_type;
    //loadDsExpressions();
    this.cleanPreview();

    this.curWidget.config.selects = oldConfig.selects;
    this.curWidget.config.keys = oldConfig.keys;
    this.curWidget.config.groups = oldConfig.groups;
    this.curWidget.config.values = [];

    this.addHelpMessage();

    this.curWidget.config.filters = oldConfig.filters;
    switch (this.curWidget.config.chart_type) {
        case 'line':
        this.curWidget.config.values.push({name: '', cols: []});
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    this.curWidget.config.values[0].cols.push(c);
                });
            });
            this.curWidget.config.valueAxis = 'vertical';
            _.each(this.curWidget.config.values, function (v) {
                v.series_type = 'line';
                v.type = 'value';
            });
            break;
        case 'pie':
            this.curWidget.config.values.push({name: '', cols: []});
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    this.curWidget.config.values[0].cols.push(c);
                });
            });
            _.each(this.curWidget.config.values, function (v) {
                v.series_type = 'pie';
                v.type = 'value';
            });
            break;
        case 'kpi':
            this.curWidget.config.values.push({name: '', cols: []});
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    this.curWidget.config.values[0].cols.push(c);
                });
            });
            this.curWidget.config.selects = JSON.parse(JSON.stringify(this.columns));
            _.each(this.curWidget.config.values, function (v) {
                v.style = 'bg-aqua';
            });
            break;
        case 'scatter':
            var i = 0;
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    if (i >= 3) {
                        this.curWidget.config.selects.push(c.col);
                        return;
                    }
                    if (!this.curWidget.config.values[i]) {
                        this.curWidget.config.values[i] = {name: '', cols: []};
                    }
                    this.curWidget.config.values[i].cols.push(c);
                    i++
                });
            });
            for (var i = 0; i < 3; i++) {
                if (!this.curWidget.config.values[i]) {
                    this.curWidget.config.values[i] = {name: '', cols: []};
                }
            }
            break;
        case 'gauge':
            this.curWidget.config.values.push({name: '', cols: []});
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    this.curWidget.config.values[0].cols.push(c);
                });
            });
            this.curWidget.config.selects = JSON.parse(JSON.stringify(this.columns));
            this.curWidget.config.styles = [
                {proportion: '0.2', color: '#228b22'},
                {proportion: '0.8', color: '#48b'},
                {proportion: '1', color: '#ff4500'}
            ];
            break;
        case 'heatMapCalendar':
            this.curWidget.config.values.push({name: '', cols: []});
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    this.curWidget.config.values[0].cols.push(c);
                });
            });
            this.curWidget.config.selects = JSON.parse(JSON.stringify(this.columns));
            _.each(this.curWidget.config.values, function (v) {
                v.dateFormat = 'yyyy-MM-dd';
                v.style = 'blue';
            });
            break;
        case 'heatMapTable':
            this.curWidget.config.values.push({name: '', cols: []});
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    this.curWidget.config.values[0].cols.push(c);
                });
            });
            this.curWidget.config.selects = JSON.parse(JSON.stringify(this.columns));
            _.each(this.curWidget.config.values, function (v) {
                v.style = 'blue';
            });
            break;
        case 'liquidFill':
            this.curWidget.config.values.push({name: '', cols: []});
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    this.curWidget.config.values[0].cols.push(c);
                });
            });
            this.curWidget.config.selects =JSON.parse(JSON.stringify(this.columns));
            // this.curWidget.config.animation = 'static';
            _.each(this.curWidget.config.values, function (v) {
                v.style = 'circle';
            });
            break;
        case 'chinaMap':
            this.curWidget.config.values.push({name: '', cols: []});
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    this.curWidget.config.values[0].cols.push(c);
                });
            });
            this.curWidget.config.valueAxis = 'vertical';
            _.each(this.curWidget.config.values, function (v) {
                v.series_type = 'scatter';
                v.type = 'value';
            });
            break;
        case 'chinaMapBmap':
            this.curWidget.config.values.push({name: '', cols: []});
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    this.curWidget.config.values[0].cols.push(c);
                });
            });
            this.curWidget.config.valueAxis = 'vertical';
            _.each(this.curWidget.config.values, function (v) {
                v.series_type = 'scatter';
                v.type = 'value';
            });
            break;
        default:
            this.curWidget.config.values.push({name: '', cols: []});
            _.each(oldConfig.values, function (v) {
                _.each(v.cols, function (c) {
                    this.curWidget.config.values[0].cols.push(c);
                });
            });
            break;
    }
    _.each(this.curWidget.config.values, function (v) {
        _.each(v.cols, function (c) {
            delete c.formatter;
        });
    });
    // this.preview('preview_widget2',this.chartype);

};


newConfig () {
    // this.curWidget.config = {};
    // this.curWidget.config.option = {};
    // this.curWidget.config.chart_type = 'table';
    // this.cleanPreview();
    // // this.curWidget.config.selects = angular.copy(this.columns);
    // this.curWidget.config.keys = [];
    // this.curWidget.config.groups = [];
    // this.curWidget.config.values = [{name: '', cols: []}];
    // this.curWidget.config.filters = [];
    this.addWatch();
};

cleanPreview () {
    // $('#preview_widget').html("");
    // $('#viewQuery_widget').html("");
    this.chartShow=false;
};

//选项卡切换
tabtoggle(string){
    this.item=string;
    console.log(this.item)
}


previewQuery () {
    this.loadingPre = true;
    this.dataservice.viewQuery({
        config: this.curWidget.config,
        datasource: this.datasource ? this.datasource.id : null,
        query: this.curWidget.query,
        datasetId: this.customDs ? undefined : this.curWidget.datasetId
    }, function (query) {
        var querybr = query.trim().replace(/\n/g, '<br/>').replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");
        $('#viewQuery_widget').html("<div class='alert alert-info' role='alert' style='text-align: left;'><p style='color: black'>" + querybr + "</p></div>");
        this.loadingPre = false;
        this.viewQueryMoal = true;
    });
};

//图表返回的数据
resizeEle(){

};

chartShow:boolean;
preview (string,type) {
    console.log(this.curWidget.config.chart_type)
    this.item=string;
    this.loadingPre = false;
    this.chartShow=true
    if(type){
        this.chartShow=true
        this.chartType=type;
    }else{
        alert('请选择图表类型')
    }

    $('#preview_widget').html("<div id='preview' style='min-height: 450px; user-select: text;'></div>");
    // --- start ---
    // 添加echarts3.6.2后这里除了第一次可以加载echarts图表，再次加载无法显示图表。
    // 完全无法找到问题下，出于无奈嵌套了一层后发现可以显示图表。囧！！
    // 具体原因没有找到，求大神帮忙解决，thanks！

    var charType = this.curWidget.config.chart_type;
    // 百度地图特殊处理
    if (charType == 'chinaMapBmap') {
        this.chartService.render($('#preview'), {
            config: this.curWidget.config,
            datasource: this.datasource ? this.datasource.id : null,
            query: this.curWidget.query,
            datasetId: this.customDs ? undefined : this.curWidget.datasetId
        },null,null,null,null,null);
        this.loadingPre = false;
    } else {
        this.chartService.render($('#preview'), {
            config: this.curWidget.config,
            datasource: this.datasource ? this.datasource.id : null,
            query: this.curWidget.query,
            datasetId: this.customDs ? undefined : this.curWidget.datasetId
        },null,null, function (option) {
            switch (this.curWidget.config.chart_type) {
                case 'line':
                    console.log(option)
                    this.previewDivWidth = 12;
                    option.toolbox = {
                        feature: {
                            dataView: {
                                show: true,
                                readOnly: true
                            }
                        }
                    };
                    break;
                case 'pie':
                    this.previewDivWidth = 12;
                    option.toolbox = {
                        feature: {
                            dataView: {
                                show: true,
                                readOnly: true
                            }
                        }
                    };
                    break;
                case 'kpi':
                    this.previewDivWidth = 6;
                    break;
                case 'table':
                    this.previewDivWidth = 12;
                    break;
                case 'funnel':
                    this.previewDivWidth = 12;
                    option.toolbox = {
                        feature: {
                            dataView: {
                                show: true,
                                readOnly: true
                            }
                        }
                    };
                    break;
                case 'sankey':
                    this.previewDivWidth = 12;
                    option.toolbox = {
                        feature: {
                            dataView: {
                                show: true,
                                readOnly: true
                            }
                        }
                    };
                    break;
                case 'map':
                    this.previewDivWidth = 12;
                    break;
                case 'areaMap':
                    this.previewDivWidth = 12;
                    break;
                case 'chinaMap':
                    this.previewDivWidth = 12;
                    break;
                case 'relation':
                    this.previewDivWidth = 12;
                    break;
            }
            this.loadingPre = false;
        }, null, !this.loadFromCache);
    }
};

add_style () {
    // this.curWidget.config.styles.push({
    //     proportion: '',
    //     color: ''
    // });
};

initColorPicker (index) {
    // $timeout(function() {
    //     $("#color_"+index).colorpicker()
    //         .on("changeColor", function(e){
    //             if($scope.curWidget.config.styles[e.target.id.split("_")[1]]){
    //                 $scope.curWidget.config.styles[e.target.id.split("_")[1]].color = e.color.toHex();
    //             }
    //         });
    // }, 100,true);
};

public saveWgtCallBack (serviceStatus) {
    // if (serviceStatus.status == '1') {
    //     this.getWidgetList();
    //     this.getCategoryList();
    //     ModalUtils.alert(this.translate.instant("COMMON.SUCCESS"), "modal-success", "sm");
    // } else {
    //     ModalUtils.alert(serviceStatus.msg, "modal-warning", "lg");
    // }
};
getwidgetData(id){
    //JSON.stringify()不能转换循环引用的结构
    let idother=id?id:197;
    let nameother= this.selectnodedata
    
    let obj={
        json:{
            id:idother,
            name:nameother.label+"_copy",
            categoryName:this.getParent(id),
            data:{
                config:{
                    option:{},
                    chart_type:'table',
                    keys:'',
                    groups:[],
                    values:[
                        {"name":"","cols":[]}
                    ],
                    filters:[]
                },
                id:2,
                expressions:[],
                filterGroups:[]
            },
            dateFilter:this.masterDashboardDateFilterColumn,
            dateFormat:this.masterDashboardDateFilterFormat
        }
    };
    return obj;
}
saveWgt (optFlag,id) {
    console.log(optFlag)
   
    console.log(this.getwidgetData(id))
    
    if (!this.validation()) {
        return;
    };
    this.validation()
    var o = {
        id:'',
        name:'',
        categoryName:'',
        data:{
            config:{},
            query:'',
            datasource:{},
            datasetId:'',
            expressions:'',
            filterGroups:[]
        },
        dateFilter:false,
        dateFormat:[]
    };
    o.name = this.widgetName.slice(this.widgetName.lastIndexOf("/") + 1).trim();
    o.categoryName = this.widgetName.substring(0, this.widgetName.lastIndexOf("/")).trim();
    if (o.categoryName == '') {
        o.categoryName = this.translate.instant("COMMON.DEFAULT_CATEGORY");
    }

    o.data.config = this.curWidget.config;
    if (this.customDs) {
        o.data.query = this.curWidget.query;
        o.data.datasource = this.datasource.id;
    } else {
        o.data.datasetId = this.curWidget.datasetId;
    }
    o.data.expressions = _.filter(this.curWidget.expressions, function (e) {
        return !this.isDsExpression(e);
    });
    o.data.filterGroups = _.filter(this.curWidget.filterGroups, function (e) {
        return !this.isDsFilter(e);
    });
    o.dateFilter = this.masterDashboardDateFilterColumn;
    o.dateFormat = this.masterDashboardDateFilterFormat;
    this.alerts = [];
    this.verify = {widgetName: true};
    if (o.name == null || o.name == "") {
        this.alerts.push({
                severity:'warn', 
                summary:'Warn Message', 
                detail:'图表名不能为空'
            });
        this.verify = {widgetName: false};
        $("#widgetName").focus();
        return;
    } else if (o.data.datasetId == undefined && this.customDs == false) {
        this.alerts.push({
            severity:'warn', 
            summary:this.translate.instant('CONFIG.WIDGET.WIDGET_NAME'), 
            detail:this.translate.instant('COMMON.NOT_EMPTY')
        });
        return;
    }

    if (this.optFlag == 'new') {
        this.liteMode = false;
        alert(1)
        this.chartsservice.savenewidget(this.getwidgetData(id)).subscribe((res)=>{
            console.log(res)
           
        })
    } else if (this.optFlag == 'edit') {
        alert(2)
        o.id = this.widgetId;
        this.liteMode = true;
        console.log(o)
        this.chartsservice.editwidget(this.getwidgetData(id)).subscribe((res)=>{
        })
    }
};


//取消
public doCancel () {
    if (this.optFlag == 'new') {
        this.newConfig();
        this.filterSelect = {};
        this.cleanPreview();
    } else {
        alert('取消')
    }
}


refreshSchema () {
    this.loadDataset(function () {
        this.curWidget.expressions = [];
        this.loadDsExpressions();
        this.curWidget.filterGroups = [];
        this.loadDsFilterGroups();
        this.buildSchema();
    });
}

public buildSchema () {
    var loadFromDataset = false;
    var dataset;
    if (!this.customDs) {
        dataset = _.find(this.datasetList, function (ds) {
            return ds.id == this.curWidget.datasetId;
        });
        if (dataset.data.schema && (dataset.data.schema.measure.length > 0 || dataset.data.schema.dimension.length > 0)) {
            loadFromDataset = true;
        }
    }
    if (loadFromDataset) {
        this.schema = dataset.data.schema;
        // $scope.alerts = [];
        this.switchLiteMode(true);
    } else {
        this.loading = true;
        this.dataservice.getColumns({
            datasource: this.datasource ? this.datasource.id : null,
            query: this.curWidget.query,
            datasetId: this.customDs ? undefined : this.curWidget.datasetId,
            reload: !this.loadFromCache,
            callback: function (dps) {
                this.loading = false;
                this.alerts = [];
                if (dps.msg == "1") {
                    this.schema = {selects: []};
                    _.each(dps.columns, function (e) {
                        this.schema.selects.push({column: e});
                    });
                    this.switchLiteMode(true);
                } else {
                    // $scope.alerts = [{msg: dps.msg, type: 'danger'}];
                    alert('有错误')
                }
            }
        });
    }
};

public deleteWgt (widget) {
    // ModalUtils.confirm(this.translate.instant("COMMON.CONFIRM_DELETE"), "modal-info", "lg", function () {
    //     $http.post("dashboard/deleteWidget.do", {id: widget.id}).success(function (serviceStatus) {
    //         if (serviceStatus.status == '1') {
    //             getWidgetList();
    //         } else {
    //             ModalUtils.alert(serviceStatus.msg, "modal-warning", "lg");
    //         }
    //         $scope.optFlag == 'none';
    //     });
    // });
};


// public getQueryView = function () {
//     if ($scope.datasource && $scope.datasource.name) {
//         return 'dashboard/getConfigView.do?type=' + $scope.datasource.type;
//     }
// };

public getChartView () {
    // if ($scope.curWidget.config && $scope.curWidget.config.chart_type) {
    //     return 'org/cboard/view/config/chart/' + $scope.curWidget.config.chart_type + '.html';
    // }
};

public getOptionsView () {
    var basePath = '../org/';
    if (this.curWidget.config && this.curWidget.config.chart_type) {
        return basePath + this.curWidget.config.chart_type + '.html';
    }
}

public schemaToSelect (schema) {
    // if (schema.selects) {
    //     return angular.copy(schema.selects);
    // } else {
    //     var selects = [];
    //     selects = selects.concat(schema.measure);
    //     _.each(schema.dimension, function (e) {
    //         if (e.type == 'level') {
    //             _.each(e.columns, function (c) {
    //                 selects.push(c);
    //             });
    //         } else {
    //             selects.push(e);
    //         }
    //     });
    //     return angular.copy(selects);
    // }
};



ignoreChanges:boolean=false
public applyModelChanges() {
    return !this.ignoreChanges;
};

private bgShow = false;
showInfo () {
    this.modalshow=true;
    console.log(this.modalshow)
    if(this.treeId){
        this.bgShow=false;
    }else{
        this.bgShow=true
    }
};

value:any;    //临时无效
selectnodedata:any;
treeId:any;
revise(data){
    console.log(data)
    this.treeId=data;
    this.widgetName=''
    this.liteMode=false;
}
//schema控制图表类型显示
//data.list
charType(data:any){
    console.log(data)
    this.schema=data.scame;
    this.optFlag=data.list
    this.treeId = data.id
    console.log(this.schema)
}
nodedata(data){
    console.log(data)
    this.selectnodedata=data

}

private searchChild (node, id){
    if(node.id == id){
      return true;
    }else{
      if(node.children){
        for(let n in node.children){
          if(this.searchChild(node.children[n], id)){
            if(!node.data.parentId){
              return node.id;
            }else{
              return node.data.parentId;
            }
          }
        }
      }
    }
  }

private getParent (id){
    let nodeList = this.widgetList;
    for(let n in nodeList){
      let result = this.searchChild(nodeList[n], id)
      if(result){
        return result;
      }
    }
  }

//获取数据集
getDataSet(ev:any){
    this.liteMode=true;
    if(ev){
        this.treeservice.getdataMenu(this.treeId).then((res)=>{
            console.log(res)
        })
    }
}
//删除节点后重新刷新数据
status(status:any){
    if(status){
        this.getTreeMenu()
    }
}

getModal(data){
    this.modalshow=data
}
copyNode () {
    console.log(this.getParent(38))
    alert(this.treeId)
    if(this.treeId){
        console.log(this.getwidgetData(this.treeId))
        this.treeservice.copyNode({json:JSON.stringify(this.getwidgetData(this.treeId))}).then((res)=>{
            if(res.status==1){
                this.getTreeMenu()
            }
        })
    }else{
        this.showInfo()
    }
};

public editNode () {
    if(this.treeId){
        this.optFlag='edit'
        alert(this.treeId)
    }else{
        this.showInfo()
    }
    var selectedNode = this.treeId;
};

public deleteNode () {
    if(this.treeId){
        this.modalshow=true;
        this.deleteShow=true;
        this.bgShow=false;
    }else{
        this.showInfo()
    }
};


//新建图表
datagroup=[
    {id:1,name:111,value:111},
    {id:2,name:222,value:222},
    {id:3,name:333,value:333}
]
handle(ev:any):void{
    console.log(ev)
    this.loadData()
    // this.charType()
    // this.curWidget.datasetId=ev
    // console.log(this.curWidget.datasetId)
}


//处理widget-chart
private datasetMeta = {};
private intervals = [];
private realtimeDataset = {};
public boardParams;
public widgetCfg;
public board:any;
private widgetFilters = {};
private datasetFilters = {};
private relationFilters = {};
public relations:any = [{},{}];
private dataFilterConditions=[];
private paramInit = 0;

private paramToFilter() {
    this.widgetFilters = [];
    this.datasetFilters = [];
    this.relationFilters = [];
    let that = this;
    //将点击的参数赋值到看板上的参数中
    //"{"targetId":3,"params":[{"targetField":"logo","value":"iphone"},{"targetField":"logo1","value":"上海市"}]}" targetField==param.name
    if(location.href.split("?")[1]) {
      var urlParam = JSON.parse(decodeURI(location.href.split("?")[1]));
      _.each(this.board.layout.rows, function (row:any) {
        _.each(row.params, function (param:any) {
          var p = _.find(urlParam.params, function (e:any) {
            return e.targetField == param.name;
          });
          if(p){
            param.values.push(p.value);
          }
        });
      });
      location.href = location.href.split("?")[0];
    }

    _.each(this.board.layout.rows, function (row:any) {
      _.each(row.params, function (param:any) {
        if (param.values.length <= 0) {
          return;
        }
        _.each(param.col, function (col:any) {
          var p = {
            col: col.column,
            type: param.type,
            values: param.values
          };
          if (_.isUndefined(col.datasetId)) {
            if (!that.widgetFilters[col.widgetId]) {
              that.widgetFilters[col.widgetId] = [];
            }
            that.widgetFilters[col.widgetId].push(p);
          } else {
            if (!that.datasetFilters[col.datasetId]) {
              that.datasetFilters[col.datasetId] = [];
            }
            that.datasetFilters[col.datasetId].push(p);
          }
        });
      });
    });
    this.updateParamTitle();
    //将点击的参数赋值到relationFilters中
    if(_.isUndefined($("#relations").val())){
      return;
    }
    var relations = this.relations;//JSON.parse($("#relations").val());
    for(var i=0;i<relations.length;i++){
      if(relations[i].targetId && relations[i].params && relations[i].params.length>0){
        for(var j=0;j<relations[i].params.length;j++) {
          var p = {
            col: relations[i].params[j].targetField,
            type: "=",
            values: [relations[i].params[j].value]
          };
          if (!this.relationFilters[relations[i].targetId]) {
            this.relationFilters[relations[i].targetId] = [];
          }
          this.relationFilters[relations[i].targetId].push(p); //relation.targetId == widgetId
        }
      }
    }
  };
     public updateParamTitle() {
        _.each(this.board.layout.rows, function (row:any) {
          _.each(row.params, function (param:any) {
            if ('slider' == param.paramType) {
              return;
            }
            var paramObj;
            switch (param.type) {
              case '=':
              case '≠':
                paramObj = param.name + ' ' + param.type + ' (' + param.values + ')';
                break;
              case '>':
              case '<':
              case '≥':
              case '≤':
                paramObj = param.name + ' ' + param.type + ' ' + param.values;
                break;
              case '(a,b]':
              case '[a,b)':
              case '(a,b)':
              case '[a,b]':
                var leftBrackets = param.type.split('a')[0];
                var rightBrackets = param.type.split('b')[1];
                paramObj = param.name + ' between ' + leftBrackets + param.values[0] + ',' + param.values[1] + rightBrackets;
                break;
            }
            param.title = param.values.length > 0 ? paramObj : undefined;
          });
        });
      }
    
private reload (widget) {
    this.paramToFilter();
    widget.widget.data = this.injectFilter(widget.widget).data;
    let idname = 'id-' + widget.widgetId;
    //百度地图特殊处理
    var charType = widget.widget.data.config.chart_type;
    if(charType == 'chinaMapBmap'){
      this.chartService.render($('#'+idname), widget.widget.data, null, this, true,null,null);
      // widget.loading = false;
    } else {
      // TODO 第三个参数 optionFilter 从哪儿获取？
      this.chartService.render($('#'+idname), widget.widget.data, null, this, true, null, widget.relations).then(function (d) {
        widget.realTimeTicket = d;
        // widget.loading = false;
      });
    }
    // TODO 第一个参数 optionFilter 从哪儿获取？
    widget.realTimeOption = {optionFilter: null, scope: this};
    
  };

  private injectFilter(widget) {
    var boardFilters = [];
    if(this.dataFilterConditions.length >= 1) {
      boardFilters = this.dataFilterConditions;
    }
    if(!_.isUndefined(this.widgetFilters[widget.id])){
      _.each(this.widgetFilters[widget.id], function(e){
        boardFilters.push(e);
      });
    }
    if(!_.isUndefined(this.datasetFilters[widget.data.datasetId])){
      _.each(this.datasetFilters[widget.data.datasetId], function(e){
        boardFilters.push(e);
      });
    }
    if(!_.isUndefined(this.relationFilters[widget.id])){
      _.each(this.relationFilters[widget.id], function(e){
        boardFilters.push(e);
      });
    }
    widget.data.config.boardFilters = boardFilters;
    // console.log("当前过滤条件...", boardFilters);
    return widget;
  };

onRenderComplete(curwidget) {
    console.log('--------------show------------');
    for(let rows of this.board.layout.rows){
      if(rows.type != 'widget'){
        continue;
      }
      for(let widget of rows.widgets){
        if(widget.widgetId === curwidget.widgetId){
          curwidget.loading = true;
          this.reload(widget);
          break;
        }
      }
    }
  }

  onReloadEvent(curwidget){
    for(let rows of this.board.layout.rows){
      if(rows.type != 'widget'){
        continue;
      }
      for(let widget of rows.widgets){
        if(widget.widgetId === curwidget.widgetId){
          curwidget.loading = true;
          this.reload(widget);
          break;
        }
      }
    }
  }

  @Input()  boardId: any;
  private intervalGroup;
  private boardloaded=false
  public timeline = [];
  public timelineFilter;

  public loadPage(reload) {
    // initLeftMenu();
    let that = this;
    this.paramInit = 0;
    this.loading = true;
    $("#relations").val(JSON.stringify([]));
    _.each(this.intervals, function (e) {
      // $interval.cancel(e);
    });
    this.intervals = [];

    if (this.board) {
      _.each(this.board.layout.rows, function (row:any) {
        _.each(row.widgets, function (widget:any) {
          widget.show = false;
        });
      });
    }
    this.http.post('http://localhost:8080/dashboard/getBoardData.do?id='+ this.boardId, {type: 'widget'} , {responseType: 'text'}).subscribe(resp => {
      that.intervalGroup = {};
      that.loading = false;
      that.board = JSON.parse(resp);
      console.log(this.board);
      that.boardloaded = true;
      _.each(that.board.layout.rows, function (row:any) {
        _.each(row.params, function (param:any) {
          if (!param.paramType) {
            param.paramType = 'selector';
          }
        });
      });

      _.each(that.board.layout.rows, function (row:any) {
        _.each(row.params, function (param) {
          that.paramInit++;
        });
      });
      if (that.board.layout.type == 'timeline') {
        that.groupTimeline();
      }
      if (that.paramInit == 0) {
        that.loadWidget(reload);
      }
    });
  };

  private initDsReloadStatus(reload) {
    var dsReloadStatus = {};
    _.each(this.board.layout.rows, function(row:any) {
      _.each(row.widgets, function (widget:any) {
        var dataSetId = widget.widget.data.datasetId;
        if (dataSetId != undefined) {
          dsReloadStatus[dataSetId] = reload;
        }
      });
    });
    return dsReloadStatus;
  };

  private loadWidget (reload) {
    this.paramToFilter();
    var that = this;
    var dsReloadStatus = this.initDsReloadStatus(reload);
    _.each(this.board.layout.rows, function (row:any) {
      _.each(row.widgets, function (widget:any) {
        if (!_.isUndefined(widget.hasRole) && !widget.hasRole) {
          return;
        }
        var dataSetId = widget.widget.data.datasetId;
        var needReload = reload;
        if (dataSetId != undefined && reload) {
          var needReload:any = dsReloadStatus[dataSetId] ? true : false;
          dsReloadStatus[dataSetId] =  false;
        }

        if (that.board.layout.type == 'timeline') {
          if (row.show) {
            widget.show = true;
          }
        } else {
          widget.show = true;
        }
      });
    });
  };

  private groupTimeline() {
    var that = this;
    that.timeline = [];
    var group = undefined;
    _.each(that.board.layout.rows, function (row:any, idx) {
      if (idx == 0) {
        that.timelineFilter = row;
        return;
      }
      row.show = false;
      if (row.node == 'parent') {
        if (group) {
          that.timeline.push(group);
        }
        group = [];
        row.show = true;
      }
      group.push(row);
    });
    that.timeline.push(group);
  };

    private initRequests(){
    let that = this;
    that.http.post('http://localhost:8080/admin/isConfig.do?type=widget', {type: 'widget'} , {responseType: 'text'}).subscribe(resp => {
      that.widgetCfg = resp;
      that.http.get('http://localhost:8080/dashboard/getBoardParam.do?boardId='+this.boardId , {responseType: 'text'}).subscribe(resp => {
        console.log('-----------getBoardParam------------');
        console.log(resp);
        if (resp) {
          let jrsp = JSON.parse(resp);
          that.boardParams = jrsp.config;
        } else {
          that.boardParams = [];
        }
        that.http.get('http://localhost:8080/dashboard/getDatasetList.do' , {responseType: 'text'}).subscribe(resp => {
          // alert(resp);
          this.datasetList = JSON.parse(resp);
          // this.datasetList = response;
          that.realtimeDataset = {};
          that.datasetMeta = {};
          that.intervals = [];
          that.datasetFilters = {};
          that.widgetFilters = {};
          that.relationFilters = {};
          that.loadPage(false);
          console.log('-----------getDatasetList------------');
        })
      })
    })
  }

};


